package com.lxk.concurrency.example.lock;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.lxk.concurrency.annoations.ThreadSafe;

/**
 * @Description 读写锁，读读不互斥，当有写就互斥
 * 							当读很多，写较少时候，可能写的就会一直阻塞（写饥饿），等不到机会
 *
 * @author 堆堆堆
 * @date 2018年5月25日 上午11:32:28
 */
@ThreadSafe
public class LockExample3 {

	private final Map<String, Data> map = new TreeMap<>();

	private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	private final Lock readLock = lock.readLock();

	private final Lock writeLock = lock.writeLock();

	public Data get(String key) {
		readLock.lock();
		try {
			return map.get(key);
		} finally {
			readLock.unlock();
		}
	}

	public Set<String> getAllKeys() {
		readLock.lock();
		try {
			return map.keySet();
		} finally {
			readLock.unlock();
		}
	}

	public Data put(String key, Data value) {
		writeLock.lock();
		try {
			return map.put(key, value);
		} finally {
			writeLock.unlock();
		}
	}

	class Data {

	}
}
